package main

import (
	"log"
	"math"
	"time"
)

//查询路径
func searchPath(mw *MyMainWindow) {
	log.Println("寻路")
	grid := mw.grid
	grid.initCloseList()
	grid.initOpenList()
	start := grid.Start
	x := start.X
	y := start.Y
	grid.addOpenList(x, y)
	go aStar(grid, mw)
}

func aStar(grid *Grids, mw *MyMainWindow) {
	s := time.Second / 2
	b := true
	for {
		sleep(s)
		if b {
			b = false
			start := grid.Start
			x := start.X
			y := start.Y

			grid.removeOpenList(x, y)
			grid.addCloseList(x, y)

			grid.addNewOpenList(x, y, x, y+1, DIR_UP)           //上
			grid.addNewOpenList(x, y, x, y-1, DIR_DOWN)         //下
			grid.addNewOpenList(x, y, x+1, y, DIR_LEFT)         //左
			grid.addNewOpenList(x, y, x-1, y, DIR_RIGHT)        //右
			grid.addNewOpenList(x, y, x+1, y+1, DIR_UP_LEFT)    //左上
			grid.addNewOpenList(x, y, x-1, y+1, DIR_UP_RIGHT)   //右上
			grid.addNewOpenList(x, y, x+1, y-1, DIR_DOWN_LEFT)  //左下
			grid.addNewOpenList(x, y, x-1, y-1, DIR_DOWN_RIGHT) //右下

			cost := 10000.0
			for i := 0; i < len(grid.OpenList.NowPoint); i++ {
				xy := grid.OpenList.NowPoint[i]
				tx := xy[0]
				ty := xy[1]
				txPoint := grid.OpenList.Get(tx, ty)
				if txPoint.IsExist {
					if cost > txPoint.F {
						cost = txPoint.F
						x = tx
						y = ty
					}
				}
			}

			log.Println(x, y)
			mw.startPoint(x, y)
			grid.Start = NewNode(x, y)
			b = true
			grid.OpenList.NowPoint = make([][]int, 0, 1)
			grid.CloseList.NowPoint = make([][]int, 0, 1)
		}
	}
}

// 得到地图上这一点的消耗值
func getMapExpense(x, y, dir int) float64 {
	if dir < 5 {
		return float64(10)
	}
	return float64(14)
}

// 得到距离的消耗值
func getDistance(x, y, ex, ey int) float64 {
	x1 := math.Abs(float64(x) - float64(ex))
	y1 := math.Abs(float64(y) - float64(ey))
	return 10*x1 + y1
}

//休眠
func sleep(sleep time.Duration) {
	time.Sleep(sleep)
}
